"""
@Author：WangYuXiang
@E-mile：Hill@3io.cc
@CreateTime：2021/4/13 16:30
@DependencyLibrary：无
@MainFunction：无
@FileDoc： 
    group.py
    文件说明
@ChangeHistory:
    datetime action why
    example:
    2021/4/13 16:30 change 'Fix bug'
        
"""
from datetime import datetime

from common.auth.models import GroupModel
from common.auth.serializers import GroupModelSerializer
from common.utils.authentication import GeneralTokenAuthenticate
from sanic_rest_framework.status import HttpStatus
from sanic_rest_framework.views import ModelViewSet, GeneralView


class GroupViewSet(ModelViewSet):
    queryset = GroupModel
    serializer_class = GroupModelSerializer
    authentication_classes = (GeneralTokenAuthenticate,)
    search_fields = ('@code',)

    async def list(self, request, *args, **kwargs):
        queryset = await self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        data = await serializer.data
        return self.success_json_response(data=data)


class GroupRoleTreeView(GeneralView):
    authentication_classes = (GeneralTokenAuthenticate,)

    async def get(self, request, *args, **kwargs):
        top_groups = await GroupModel.filter(parent=None).all()
        tree = await self._recursive_parent_group(top_groups)
        return self.success_json_response(tree)

    async def _recursive_parent_group(self, groups) -> list:
        """递归得到父级组织机构权限"""
        group_list = []
        for group in groups:
            child = await group.child
            if child:
                child = await self._recursive_parent_group(child)
            group_dict = {
                'id': group.id,
                'label': group.name,
                'code': group.code,
                'children': [],
                'is_role': False,
                'parent_id': group.parent_id
            }
            roles = await group.roles.all().values('code', 'name', 'id', 'group_id')
            role_dict_list = []
            for role in roles:
                role['label'] = role.pop('name')
                role['parent_id'] = role.pop('group_id')
                role.update({'is_role': True, 'child': []})
                role_dict_list.append(role)
            group_dict['children'].extend(role_dict_list)
            group_dict['children'].extend(child)
            group_list.append(group_dict)
        return group_list


class GroupEmployUserListView(GeneralView):
    """组织下聘任的用户列表"""
    authentication_classes = (GeneralTokenAuthenticate,)

    async def get(self, request, pk, *args, **kwargs):
        group = await GroupModel.get_or_none(id=pk)
        if not group:
            return self.error_json_response(msg='不存在资源%s' % pk, http_status=HttpStatus.HTTP_404_NOT_FOUND)

        users = await self._recursive_group_user([group])
        return self.success_json_response(users)

    async def _recursive_group_user(self, groups) -> list:
        """递归得到父级组织机构权限"""
        group_users = []
        for group in groups:
            child = await group.child
            if child:
                child_group_users = await self._recursive_group_user(child)
                group_users.extend(child_group_users)
            roles = await group.roles.all()
            for role in roles:
                users = await role.users.all().values('id', 'account', 'nickname', 'is_active', 'is_super_admin', 'login_datetime')
                for user in users:
                    user['role'] = role.name
                    user['group'] = group.name
                    login_datetime = user.get('login_datetime', None)
                    if isinstance(login_datetime, datetime):
                        user['login_datetime'] = login_datetime.strftime("%Y-%m-%d %H:%M:%S")
                    group_users.append(user)
        return group_users
